<?php namespace Common\Model;
use Hdphp\Model\Model;

class sc_category extends Model{
	
	//指定表
	protected $table="sc_category";
	
	//自动验证
	protected $validate=array(
	   array('cname','required','分类名称不能为空！',3,3),
	   array('cname','maxlen:80','分类名不能超过80个字符',3,3),
	   array('csort','required','排序不能为空！',3,3),
	   array('sc_type_tid','required','所属类型不能为空！',3,3)
	);
	
	//获取分类信息
	public function getCategory(){	
		return $this->orderBy('csort','ASC')->get();
	}
	
	//添加分类
	public function addCate(){
		if(!$this->create()) return false;
		$this->add(); return true;
	}
	
	//获取添加子分类时的父级分类
	public function getFather(){
		$cid=Q('get.cid');
		return $this->where('cid',$cid)->field('cid','cname')->find();	
	}
	
	
	//删除分类
	public function delCate(){
		$cid=Q('get.cid');
		$pid=$this->where('cid',$cid)->pluck('pid');
		$this->where('pid',$cid)->update(['pid'=>$pid]);
		return $this->where('cid',$cid)->delete();
	}
	
	
	
	
	//前台首页部分···········································
	//首页获取分类信息
	public function getIndexCategory(){
		$CateData=$this->where('pid',0)->get();
		foreach($CateData as $k=>$v){
			$secondPid=$v['cid'];
			$CateData[$k]['second']=$this->where('pid',$secondPid)->get();
			$CateData[$k]['secondLimit']=$this->where('pid',$secondPid)->limit(3)->get();
		}
		return $CateData;	
	}
	

    //获取当前Cid所属分类的所有分类信息
    public function getAllCateByCid($data,$pid){

		static $Pcid='';
			foreach($data as $v){
	        	if($v['cid']==$pid){
	        		$Pcid=$v['cid'];
	        		$pid=$this->getAllCateByCid($data,$v['pid']);
	        	}
            }
	        return $Pcid;
    }


	
	//获取当前分类cid,查询所有子集的cid
	public function getSonsCid($data,$cid){
       $temp=[];
	   foreach($data as $v){
	   	  if($v['pid'] == $cid){
	   	  	$temp[]=$v['cid'];
			$temp=array_merge($temp,$this->getSonsCid($data, $v['cid']));
	   	  }
	   }
	
      return $temp;
		
	}
	
	
	
	public function getCateByNowCid($data,$pid){
		//$pid=$this->where('cid',$cid)->pluck('pid');
		$temp=[];
	    foreach($data as $v){
			if($v['cid'] == $pid){
				$temp[]=$this->where('cid',$v['cid'])->find();
				$temp=array_merge($temp,$this->getCateByNowCid($data,$v['pid']));	
			}
	    }
         return $temp; 	
	}
	
	
	//获取顶级分类下的一级分类
	public function getTopSons(){
		return $this->where('pid',0)->field('cid')->get();
	}
	
	
} 
	
	
	
?>